#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

#include <psp2/apputil.h>
#include <psp2/system_param.h>

#include "utils.h"
#include "patch.h"
#include "jni.h"

int __android_log_vprint(int prio, const char *tag, const char *fmt, ...)
{
#ifdef DEBUG
	va_list list;
	char string[4096];

	va_start(list, fmt);
	vsprintf(string, fmt, list);
	va_end(list);

	debugPrintf("%s: %s\n", tag, string);
#endif
	return 0;
}

int __android_log_print(int prio, const char *tag, const char *fmt, ...)
{
#ifdef DEBUG
	va_list list;
	char string[4096];

	va_start(list, fmt);
	vsprintf(string, fmt, list);
	va_end(list);

	debugPrintf("%s: %s\n", tag, string);
#endif
	return 0;
}

void *Android_JNI_GetEnv(void)
{
	debugPrintf("Android_JNI_GetEnv called\n");
	return fake_env;
}

int Android_JNI_FileOpen(char *a1, int a2)
{
	debugPrintf("Android_JNI_FileOpen called\n");
	return -1;
}

unsigned int Android_JNI_FileRead(char *a1, void *buf, unsigned int a3, int a4)
{
	debugPrintf("Android_JNI_FileRead called\n");
	return -1;
}

int64_t Android_JNI_FileSeek(char *a1, int64_t a2, int a3)
{
	debugPrintf("Android_JNI_FileSeek called\n");
	return -1;
}

int Android_JNI_FileClose(char *a1)
{
	debugPrintf("Android_JNI_FileClose called\n");
	return -1;
}

int64_t Android_JNI_FileSize(int a1)
{
	debugPrintf("Android_JNI_FileSize called\n");
	return -1;
}

int Android_JNI_GetLocalID()
{
	switch (language)
	{
	case SCE_SYSTEM_PARAM_LANG_CHINESE_T:
		return 0;
	case SCE_SYSTEM_PARAM_LANG_CHINESE_S:
		return 1;
	default:
		return 2;
	}
}

int Android_APKX_SetFile(const char *dirpath, const char *filename)
{
	if (strcasecmp(filename, "TapTap_icon.png") == 0)
		return -1;

	char path[1024];
	snprintf(path, 1024, "%s/%s/%s", DATA_PATH, dirpath, filename);
	fatal_error("Missing: %s", path);
	return -1;
}

int SDL_Android_Init()
{
	debugPrintf("SDL_Android_Init called\n");
	return 0;
}

int GetAndroidFileIsExists(char *path)
{
	trimString(path);
	int ret = file_exists(path);
	debugPrintf("GetAndroidFileIsExists: %s, return: %d\n", path, ret);
	return ret;
}

int initPatchAndroid()
{
	hook_addr(so_symbol(&so_mod, "_Z20Android_APKX_SetFilePKcS0_"), (uintptr_t)&Android_APKX_SetFile);
	hook_addr(so_symbol(&so_mod, "_Z22GetAndroidFileIsExistsPKc"), (uintptr_t)&GetAndroidFileIsExists);

	return 0;
}